var express = require('express')
var expressRouter = express.Router()
var rp = require('request-promise'),
    debug = require('debug')('react-demo')

import _ from 'lodash'
import Promise from 'bluebird';
import React from 'react'
import ReactDOM from 'react-dom/server'
import { match, RouterContext, browserHistory } from 'react-router'
import { createStore, combineReducers, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import * as reducers from '../src/reducers';
import { syncHistoryWithStore, routerReducer } from 'react-router-redux'
import ReduxThunk from 'redux-thunk'

import main from '../src/main'

var configFile = 'config.'+process.env.NODE_ENV+'.json'
var config = require('../config/'+configFile);

/**
 * A patch to Resolve passing extra server props to RouterContext and components issue
 * ref: http://stackoverflow.com/questions/37261487/react-router-server-rendering-with-server-props
 */
function createElementFn(serverProps) {
  return function(Component, props) {
    return <Component {...serverProps} {...props} />
  }
}

expressRouter.use(function(req, res, next) {

  if (req.originalUrl.toLowerCase().indexOf('/login', 0) === 0) {
    return next();
  }

  var token = req.cookies.access_token;
  if (!token) {
    return res.redirect('/login')
  }

  debug(token)
  var option = {
    method: 'POST',
    uri: config.apiHost+'/api/auth/',
    body: {
      access_token: token
    },
    headers: {
      authorization: 'Bearer '+token
    },
    json: true
  }

  rp(option)
    .then(function(result) {
      debug(result);
      if (result.success) {
        var sysuser = result.data
        console.log(sysuser)
        var appId = sysuser.WorkingProperty?sysuser.WorkingProperty.appId: ''
        req.sysuser = sysuser
        res.cookie('appId', appId, {expires: new Date(Date.now() + 24 * 60 * 60 * 7 * 1000)})

        return next();
      }else {
        return res.redirect('/login')
      }
    })
    .catch(function(err) {
      console.error(err);
      if (err.statusCode == 403) {
        return res.redirect('/login')
      }
      return next(err)
    })
})


expressRouter.use(function(req, res, next){
  if (req.originalUrl.toLowerCase().indexOf('login', 0) >= 0 ||
      req.originalUrl.toLowerCase().indexOf('logout', 0) >= 0) {
    return next();
  }
  const store = applyMiddleware(ReduxThunk)(createStore)(
    combineReducers(
      _.assign(reducers, {
        routing: routerReducer
      })
    )
  )

  // Note that req.url here should be the full URL path from
  // the original request, including the query string.
  match({ routes: main.routes, location: req.url }, function(error, redirectLocation, renderProps){
    if (error) {
      res.status(500).send(error.message)
    } else if (redirectLocation) {
      res.redirect(302, redirectLocation.pathname + redirectLocation.search)
    } else if (renderProps) {

      // You can also check renderProps.components or renderProps.routes for
      // your "not found" component or route respectively, and send a 404 as
      // below, if you're using a catch-all route.

      var sysuser = req.sysuser;

      var initialState = {
        config: config,
        sysuser: sysuser,
        username: sysuser.username,
        name: sysuser.firstName+sysuser.lastName,
        userType: sysuser.userType,
        wechat: [{
          name: sysuser.WorkingProperty?sysuser.WorkingProperty.name:'',
          appId: sysuser.WorkingProperty?sysuser.WorkingProperty.appId: ''
        }]
      }
      const serverProps = { initialState: initialState };


      var dom = ReactDOM.renderToString(
         <Provider store={store}>
          <RouterContext {...renderProps} createElement={createElementFn(serverProps)} />
         </Provider>
        );

      console.log("==>", dom);

      const initialReduxState = store.getState();

      console.log("store ==>", initialReduxState);

      var last_leave = req.cookies['kerry_leave']
      console.log(last_leave)
      var now = new Date().getTime()
      if (last_leave && !isNaN(last_leave)) {
        if (now - last_leave > 5 * 60 * 1000) {
          res.cookie('access_token', '')
          return res.redirect('/login')
        }
      }

      res.render('index', { react: dom, initialState: initialState,
                            initialReduxState:initialReduxState, environment: process.env.NODE_ENV } );

    } else {
      res.status(404).send('Not found')
    }
  })
})

expressRouter.get("/login", function(req, res, next) {
  return res.render('login')
})

expressRouter.get("/logout", function(req, res, next) {
  console.log("logout")
  res.cookie('access_token', '');
  return res.redirect('/login')
})


module.exports = expressRouter;
